package cn.zhoutingrui.pethome.system.dept.service.impl;

import cn.zhoutingrui.pethome.base.service.impl.BaseServiceImpl;
import cn.zhoutingrui.pethome.config.BussnisEptional;
import cn.zhoutingrui.pethome.system.dept.domain.Department;
import cn.zhoutingrui.pethome.system.dept.domain.DeptEchart;
import cn.zhoutingrui.pethome.system.dept.mapper.DepartmentMapper;
import cn.zhoutingrui.pethome.system.dept.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ztr
 * @since 2023-01-13
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> getTree() {
        //获取顶级父类的集合
        List<Department> depts = departmentMapper.findAll();
        List<Department> one = depts.stream()
                                    .filter(department -> department.getParentId() == null )
                                    .collect(Collectors.toList());
        for (Department dept : depts) {
            if (dept.getParentId()!=null){
                for (Department parent : depts) {
                    if (dept.getParentId()==parent.getId()){
                        parent.getChildren().add(dept);
                        break;
                    }
                }
            }
        }
        return one;
    }

    @Override
    public List<DeptEchart> countEmpByDept() {
        return departmentMapper.countEmpByDept();
    }

    //添加部门

    @Override
    public void add(Department department) {
        super.add(department);
        extracted(department);
    }

    private void extracted(Department department) {
        //获取父类id
        Long parentId = department.getParentId();
        if (parentId!=null){
            Department parent = departmentMapper.findById(parentId);
            String dirpath = parent.getDirPath();
            String path=dirpath+"/"+ department.getId();
            department.setDirPath(path);
        }else {
            String path="/"+ department.getId();
            department.setDirPath(path);
        }
        super.update(department);
    }

    @Override
    public void update(Department department) {
        extracted(department);
    }

    //删除
    public void delete(Long id){
        Long count = departmentMapper.findByParentId(id);
        if (count!=0){
            throw new BussnisEptional("当前部门存在下级,无法删除");
        }
        departmentMapper.delete(id);
    }

}
